<?php

namespace App\Admin\RowActions;

use App\Models\Message;
use Dcat\Admin\Grid\RowAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Delete extends RowAction
{
    protected $model;

    public function __construct(string $model = null)
    {
        $this->model = $model;
    }

    /**
     * 标题
     *
     * @return string
     */
    public function title()
    {
        return '<button type="button" style="background-color: red;" class="layui-btn">删除</button>';
    }

    /**
     * 设置确认弹窗信息，如果返回空值，则不会弹出弹窗
     *
     * 允许返回字符串或数组类型
     *
     * @return array|string|void
     */
    public function confirm()
    {
        return [
            "删除？",
            '是否删除帖子？',
        ];
    }

    /**
     * 处理请求
     *
     * @param Request $request
     *
     * @return \Dcat\Admin\Actions\Response
     */
    public function handle(Request $request)
    {
        $id = $this->getKey();

        $model = $request->get('model');

        $topic = $model::find($id);
        if (!$topic) {
            return $this->response()->error('参数错误');
        }

        DB::beginTransaction();

        try {
            $topic->delete();
            $topic->topicComment()->delete();
            $topic->topicTheme()->detach();

            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            log_exception('删除帖子异常', $e);
            return $this->response()->error('删除失败');
        }

        return $this->response()->success("删除成功")->refresh();
    }

    /**
     * 设置要POST到接口的数据
     *
     * @return array
     */
    public function parameters()
    {
        return [
            'model' => $this->model,
        ];
    }
}
